package web_controller

import (
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"strings"
	"transport/framework/fw_db/fw_db_self"
	"transport/framework/fw_jwt"
	"transport/framework/fw_utils"
	"transport/web/web_mapper"
	"transport/web/web_model"
	"transport/web/web_vo"
)

type authDriverController struct {
}

func (controller *authDriverController) login(c *gin.Context) {
	var data web_vo.LoginDriver
	err := c.ShouldBindJSON(&data)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	driverMapper := web_mapper.DriverMapper{
		Ctx:  c,
		DB:   fw_db_self.GetSqliteDB(),
		Lock: fw_db_self.GetSqliteLock(),
	}
	userItem, err := driverMapper.QueryByAccount(data.Account)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	_, err = fw_utils.CompareHashAndPassword(userItem.Pwd, data.Pwd)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	token, err, claims := fw_jwt.GenJwt(userItem.ID, userItem.Account, userItem.Phone)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	fw_utils.OK(c, map[string]interface{}{
		"userInfo":     userItem,
		"token":        token,
		"account":      userItem.Account,
		"failure_time": claims.ExpiresAt,
	}, "ok")
}
func (controller *authDriverController) SetAccount(c *gin.Context) {
	var data web_model.TransDriver
	err := c.ShouldBindJSON(&data)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	var hash []byte
	if hash, err = bcrypt.GenerateFromPassword([]byte(strings.TrimSpace(data.Pwd)), bcrypt.DefaultCost); err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	data.Pwd = string(hash)
	mapper := web_mapper.DriverMapper{
		DB:   fw_db_self.GetSqliteDB(),
		Ctx:  c,
		Lock: fw_db_self.GetSqliteLock(),
	}
	_, err = mapper.CreateOrUpdate(&data)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	fw_utils.OK(c, "", "ok")
}
func (controller *authDriverController) EditPwd(c *gin.Context) {
	var data web_model.SysUser
	err := c.ShouldBindJSON(&data)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	var hash []byte
	if hash, err = bcrypt.GenerateFromPassword([]byte(strings.TrimSpace(data.Password)), bcrypt.DefaultCost); err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	data.Password = string(hash)
	mapper := web_mapper.UserMapper{
		DB:   fw_db_self.GetSqliteDB(),
		Ctx:  c,
		Lock: fw_db_self.GetSqliteLock(),
	}
	_, err = mapper.CreateOrUpdate(&data)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	fw_utils.OK(c, "", "ok")
}
func AuthDriverRoute(r *gin.Engine) {
	controller := authDriverController{}
	v1 := r.Group("/trans")
	{
		v1.POST("/v1/authDriver/login", controller.login)
		v1.POST("/v1/authDriver/editPwd", controller.EditPwd)
		v1.POST("/v1/authDriver/setAccount", controller.SetAccount)
	}
}
